<template>
  <div class="qr-code-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>溯源二维码管理</h1>
      <p>生成、下载和扫描溯源二维码</p>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：二维码生成 -->
      <div class="qr-generator-section">
        <h2 class="section-title">生成二维码</h2>



        <!-- 二维码样式设置 -->
        <div class="style-settings">
          <div class="form-row">
            <div class="form-group">
              <label for="qrSize" class="form-label">尺寸：{{ size }}px</label>
              <input type="range" id="qrSize" v-model.number="size" min="100" max="500" step="50" class="range-input">
            </div>

            <div class="form-group">
              <label for="qrColor" class="form-label">颜色：</label>
              <input type="color" id="qrColor" v-model="color" class="color-input">
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <button class="btn btn-secondary" @click="download" :disabled="!hasGenerated">
            下载二维码
          </button>
          <button type="primary" @click="GoGoods()">
            返回商品页面
          </button>
        </div>
      </div>

      <!-- 中间：二维码预览 -->
      <div class="qr-preview-section">
        <h2 class="section-title">二维码预览</h2>
        <div class="preview-container">
          <div class="canvas-wrapper" :style="{ width: size + 'px', height: size + 'px' }">
            <canvas ref="canvasRef"></canvas>
            <div v-if="isGenerating" class="loading-overlay">
              <div class="loading-spinner"></div>
            </div>
          </div>
          <div v-if="!hasGenerated" class="preview-tip">
            点击"生成二维码"按钮查看预览
          </div>
        </div>
      </div>
    </div>

    <!-- 功能分隔线 -->
    <div class="divider">
      <span class="divider-text">二维码识别</span>
    </div>

    <!-- 二维码识别区域 -->
    <div class="qr-reader-section">
      <div class="reader-tabs">
        <button class="tab-btn" :class="{ active: activeTab === 'upload' }" @click="activeTab = 'upload'">
          上传图片识别
        </button>
        <button v-if="cameraSupported" class="tab-btn" :class="{ active: activeTab === 'camera' }"
          @click="activeTab = 'camera'">
          摄像头扫码
        </button>
      </div>

      <!-- 上传图片识别 -->
      <div v-if="activeTab === 'upload'" class="reader-content">
        <div class="upload-area">
          <input type="file" id="fileUpload" accept="image/*" @change="onFileChange" class="file-input">
          <label for="fileUpload" class="upload-label">
            <div class="upload-icon">📁</div>
            <div class="upload-text">点击上传图片识别二维码</div>
            <div class="upload-hint">支持JPG、PNG等格式</div>
          </label>
        </div>

        <!-- 识别结果 -->
        <div v-if="result" class="result-section">
          <h3 class="result-title">识别结果：</h3>
          <div class="result-content">
            {{ result }}
          </div>
        </div>
      </div>

      <!-- 摄像头扫码 -->
      <div v-else-if="activeTab === 'camera'" class="reader-content">
        <div class="camera-container">
          <video ref="videoRef" autoplay muted playsinline class="camera-feed"
            :class="{ active: cameraRunning }"></video>
          <div v-if="!cameraRunning" class="camera-placeholder">
            <div class="camera-icon">📷</div>
            <div class="camera-text">摄像头未启动</div>
          </div>
        </div>

        <div class="camera-controls">
          <button class="btn btn-primary" @click="startCamera" :disabled="cameraRunning">
            打开摄像头
          </button>
          <button class="btn btn-danger" @click="stopCamera" :disabled="!cameraRunning">
            关闭摄像头
          </button>
        </div>

        <!-- 扫码结果 -->
        <div v-if="liveResult" class="result-section">
          <h3 class="result-title">扫码结果：</h3>
          <div class="result-content">
            {{ liveResult }}
          </div>
        </div>
      </div>
    </div>
    <!-- 通知提示 -->
    <div v-if="notification.show" class="notification" :class="notification.type">
      {{ notification.message }}
    </div>
  </div>
</template>
<script setup>
import { ref, onUnmounted, onMounted } from 'vue'
import QRCode from 'qrcode'
import jsQR from 'jsqr'
import { BrowserMultiFormatReader } from '@zxing/library'
import { useRouter } from 'vue-router'
const router = useRouter();
//返回
const GoGoods = () => {
  router.push("Goods")
}
// 二维码基本配置
const text = ref('')
const size = ref(200)
const color = ref('#000000')
const canvasRef = ref(null)
const result = ref('')
const liveResult = ref('')
const videoRef = ref(null)
const codeReader = new BrowserMultiFormatReader()
let cameraRunning = false
// 状态管理
const isGenerating = ref(false)
const hasGenerated = ref(false)
const activeTab = ref('upload')
const cameraSupported = 'mediaDevices' in navigator

// 通知组件状态
const notification = ref({
  show: false,
  message: '',
  type: 'success' // success, error, info
})

// 生命周期钩子
onMounted(() => {
  // 从localStorage获取数据填充二维码内容
  const companyName = localStorage.getItem("Companyname") || ''
  const creator = localStorage.getItem("Creator") || ''
  const createTime = localStorage.getItem("Createtime") || ''

  text.value = `${companyName}${creator}${createTime}`
  generate();
})

/**
 * 生成二维码
 */
const generate = async () => {
  if (!text.value || !canvasRef.value) {
    showNotification('请输入二维码内容', 'error')
    return
  }

  isGenerating.value = true

  try {
    // 生成二维码
    await QRCode.toCanvas(canvasRef.value, text.value, {
      width: size.value,
      color: {
        dark: color.value,
        light: '#ffffff'
      },
      errorCorrectionLevel: 'H' // 高容错级别
    })

    hasGenerated.value = true
    showNotification('二维码生成成功', 'success')
  } catch (error) {
    console.error('生成二维码失败:', error)
    showNotification('生成二维码失败，请重试', 'error')
  } finally {
    isGenerating.value = false
  }
}

/**
 * 下载二维码图片
 */
const download = () => {
  if (!canvasRef.value) return

  try {
    const canvas = canvasRef.value
    const link = document.createElement('a')

    // 设置下载文件名，添加时间戳避免覆盖
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    link.download = `traceability-qrcode-${timestamp}.png`

    // 将canvas内容转换为图片URL
    link.href = canvas.toDataURL('image/png')

    // 触发下载
    link.click()
    showNotification('二维码下载成功', 'success')
  } catch (error) {
    console.error('下载二维码失败:', error)
    showNotification('下载二维码失败，请重试', 'error')
  }
}

/**
 * 处理文件上传，识别图片中的二维码
 */
const onFileChange = async (e) => {
  const file = e.target.files[0]
  if (!file) return

  // 重置结果状态
  result.value = ''

  try {
    const img = new Image()
    const reader = new FileReader()

    // 读取文件并加载图片
    await new Promise((resolve, reject) => {
      reader.onload = (event) => {
        img.onload = resolve
        img.onerror = reject
        img.src = event.target.result
      }
      reader.onerror = reject
      reader.readAsDataURL(file)
    })

    // 创建canvas进行二维码识别
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')
    canvas.width = img.width
    canvas.height = img.height
    ctx.drawImage(img, 0, 0)

    // 获取图片数据并使用jsQR库识别
    const imageData = ctx.getImageData(0, 0, img.width, img.height)
    const code = jsQR(imageData.data, img.width, img.height)

    // 显示识别结果
    result.value = code?.data || '未识别出二维码'

    if (code) {
      showNotification('二维码识别成功', 'success')
    } else {
      showNotification('未识别出二维码，请尝试清晰的图片', 'info')
    }
  } catch (error) {
    console.error('识别二维码失败:', error)
    result.value = '识别二维码时发生错误'
    showNotification('识别二维码失败，请重试', 'error')
  }

  // 重置文件输入，允许重复选择同一文件
  e.target.value = ''
}

/**
 * 打开摄像头扫码
 */
const startCamera = async () => {
  if (cameraRunning || !videoRef.value) return

  try {
    cameraRunning = true
    liveResult.value = ''

    // 获取摄像头设备并开始扫码
    const videoInputDevices = await codeReader.listVideoInputDevices()
    const selectedDeviceId = videoInputDevices[0]?.deviceId

    codeReader.decodeFromVideoDevice(selectedDeviceId, videoRef.value, (res) => {
      if (res && res.getText() !== liveResult.value) {
        liveResult.value = res.getText()
        showNotification('扫码成功', 'success')
      }
    })

    showNotification('摄像头已启动', 'success')
  } catch (e) {
    console.error('摄像头扫码失败', e)
    cameraRunning = false
    showNotification('无法启动摄像头，请检查设备权限', 'error')
  }
}

/**
 * 关闭摄像头
 */
const stopCamera = () => {
  if (!cameraRunning) return

  cameraRunning = false
  codeReader.reset()
  showNotification('摄像头已关闭', 'info')
}

/**
 * 显示通知提示
 */
const showNotification = (message, type = 'info') => {
  notification.value = {
    show: true,
    message,
    type
  }

  // 3秒后自动隐藏通知
  setTimeout(() => {
    notification.value.show = false
  }, 3000)
}

/**
 * 清理函数，组件卸载时执行
 */
onUnmounted(() => {
  stopCamera()
})
</script>

<style scoped>
/* 基础样式重置 */
* {
  box-sizing: border-box;
}

.qr-code-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

/* 页面标题样式 */
.page-header {
  text-align: center;
  color: white;
  margin-bottom: 30px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  backdrop-filter: blur(10px);
}

.page-header h1 {
  font-size: 28px;
  margin: 0 0 10px 0;
  font-weight: 600;
}

.page-header p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

/* 主要内容区域 */
.main-content {
  display: flex;
  gap: 20px;
  max-width: 1000px;
  margin: 0 auto 30px;
}

/* 二维码生成区域 */
.qr-generator-section,
.qr-preview-section {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.qr-generator-section {
  flex: 1;
}

.qr-preview-section {
  width: 350px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.section-title {
  color: #333;
  font-size: 20px;
  margin-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
  width: 100%;
}

/* 表单元素样式 */
.form-group {
  margin-bottom: 20px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.form-row .form-group {
  flex: 1;
}

.form-label {
  display: block;
  font-weight: 500;
  margin-bottom: 8px;
  color: #555;
  font-size: 14px;
}

.form-input {
  width: 100%;
  padding: 10px 12px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
}

.input-tip {
  font-size: 12px;
  color: #888;
  margin-top: 5px;
  font-style: italic;
}

/* 样式设置控件 */
.range-input {
  width: 100%;
  height: 6px;
  border-radius: 3px;
  background: #ddd;
  outline: none;
  -webkit-appearance: none;
}

.range-input::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #667eea;
  cursor: pointer;
}

.color-input {
  width: 50px;
  height: 40px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

/* 按钮样式 */
.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
  text-decoration: none;
  display: inline-block;
  text-align: center;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-primary {
  background: #667eea;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #5a67d8;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-secondary {
  background: #4299e1;
  color: white;
}

.btn-secondary:hover:not(:disabled) {
  background: #3182ce;
  transform: translateY(-1px);
}

.btn-danger {
  background: #e53e3e;
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background: #c53030;
  transform: translateY(-1px);
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-top: 20px;
}

/* 二维码预览样式 */
.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex: 1;
}

.canvas-wrapper {
  position: relative;
  display: inline-block;
  background: white;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.preview-tip {
  color: #888;
  font-size: 14px;
  text-align: center;
  margin-top: 20px;
}

/* 加载动画 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

/* 分隔线样式 */
.divider {
  display: flex;
  align-items: center;
  margin: 30px 0;
}

.divider:before,
.divider:after {
  content: '';
  flex: 1;
  height: 1px;
  background: rgba(255, 255, 255, 0.3);
}

.divider-text {
  padding: 0 20px;
  color: white;
  font-weight: 500;
  font-size: 16px;
}

/* 二维码识别区域 */
.qr-reader-section {
  background: white;
  border-radius: 12px;
  padding: 25px;
  max-width: 1000px;
  margin: 0 auto;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

/* 标签页样式 */
.reader-tabs {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
}

.tab-btn {
  padding: 8px 20px;
  background: none;
  border: none;
  color: #666;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  border-bottom: 2px solid transparent;
  transition: all 0.3s;
}

.tab-btn.active {
  color: #667eea;
  border-bottom-color: #667eea;
}

.tab-btn:hover:not(.active) {
  color: #5a67d8;
}

/* 识别内容区域 */
.reader-content {
  min-height: 300px;
}

/* 上传区域样式 */
.upload-area {
  margin-bottom: 20px;
}

.file-input {
  display: none;
}

.upload-label {
  display: block;
  padding: 40px 20px;
  border: 2px dashed #e0e0e0;
  border-radius: 10px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fafafa;
  text-align: center;
}

.upload-label:hover {
  border-color: #667eea;
  background: #f0f4ff;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.upload-text {
  font-weight: 500;
  color: #555;
  margin-bottom: 5px;
}

.upload-hint {
  font-size: 12px;
  color: #888;
}

/* 摄像头区域样式 */
.camera-container {
  position: relative;
  width: 100%;
  max-width: 400px;
  margin: 0 auto 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.camera-feed {
  width: 100%;
  height: auto;
  display: block;
  opacity: 0;
  transition: opacity 0.3s;
}

.camera-feed.active {
  opacity: 1;
}

.camera-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  color: #888;
}

.camera-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.camera-text {
  font-size: 14px;
}

.camera-controls {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-bottom: 20px;
}

/* 结果显示区域 */
.result-section {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.result-title {
  margin-top: 0;
  color: #333;
  font-size: 16px;
  margin-bottom: 10px;
}

.result-content {
  background: white;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #dee2e6;
  font-family: 'Courier New', monospace;
  white-space: pre-wrap;
  word-break: break-all;
  min-height: 60px;
  font-size: 13px;
}

/* 通知样式 */
.notification {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: 12px 20px;
  border-radius: 8px;
  color: white;
  font-weight: 500;
  z-index: 1000;
  animation: slideIn 0.3s ease-out;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }

  to {
    transform: translateX(0);
    opacity: 1;
  }
}

.notification.success {
  background: #38a169;
}

.notification.error {
  background: #dc2626;
}

.notification.info {
  background: #4299e1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qr-code-container {
    padding: 15px;
  }

  .main-content {
    flex-direction: column;
  }

  .qr-preview-section {
    width: 100%;
    margin-top: 20px;
  }

  .form-row {
    flex-direction: column;
    gap: 15px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .action-buttons .btn {
    width: 100%;
  }

  .reader-tabs {
    flex-direction: column;
  }

  .tab-btn {
    width: 100%;
    text-align: left;
  }

  .camera-controls {
    flex-direction: column;
  }

  .camera-controls .btn {
    width: 100%;
  }
}
</style>
